import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

let cartList = JSON.parse(localStorage.getItem('cartList')) || []
export default new Vuex.Store({
  state: {
    cartList
  },
  mutations: {
    // 加入购物车
    addShopCart (state, goodsMsg) {
      let goods = state.cartList.find(item => item.id == goodsMsg.id)
      if (goods) {
        goods.count += goodsMsg.count
      } else {
        state.cartList.push(goodsMsg)
      }
      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    },
    // 更新cartList
    editCartList (state, newCartList) {
      localStorage.setItem('cartList', JSON.stringify(newCartList))
    },
    // 改变商品选择状态
    changeSelect (state, goodMsg) {
      let good = state.cartList.find(item => item.id == goodMsg.id)
      good.isSelect = goodMsg.isSelect
      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    },
    // 改变全选状态
    allSelect (state, val) {
      state.cartList.forEach(item => {
        item.isSelect = val
      })
      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    },
    // 删除商品
    delGood (state, id) {
      let index = state.cartList.findIndex(item => item.id == id)
      state.cartList.splice(index, 1)
      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    },
    // 修改商品数量
    updateCount (state, obj) {
      let good = state.cartList.find(item => item.id == obj.id)
      good.count = obj.count
      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    }
  },
  getters: {
    // 购物车徽标
    getCount (state) {
      let count = 0
      state.cartList.forEach(item => {
        count += item.count
      })
      return count
    },
    // 结算价格
    getGoodsPrice (state) {
      let price = 0
      state.cartList.forEach(item => {
        if (item.isSelect) {
          price += parseInt(item.new_price) * parseInt(item.count)
        }
      })
      return price * 100
    },
    // 获取商品状态
    getSelect (state) {
      let obj = {}
      state.cartList.forEach(item => {
        obj[item.id] = item.isSelect
      })
      return obj
    }
  }
})
